package com.wanglei.ssm.controller;

import com.wanglei.ssm.domain.Permission;
import com.wanglei.ssm.domain.Role;
import com.wanglei.ssm.service.PermissionService;
import com.wanglei.ssm.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@RequestMapping("/role")
@Controller
public class RoleController {

    @Autowired
    private RoleService roleService;

    @Autowired
    private PermissionService permissionService;

    @RequestMapping("/findAll.do")
    public ModelAndView findAll(ModelAndView mv) throws Exception {
        List<Role> roleList = roleService.findAll();
        mv.addObject("roleList", roleList);
        mv.setViewName("role-list");
        return mv;
    }

    @RequestMapping("/save.do")
    public String save(Role role) throws Exception {
        roleService.save(role);
        return "redirect:findAll.do";
    }

    @RequestMapping("/findRoleByIdAndAllPermission.do")
    public ModelAndView findRoleByIdAndAllPermission(@RequestParam(name = "id") String roleId) throws Exception {
        ModelAndView mv = new ModelAndView();
        // 查询角色信息
        Role role = roleService.findById(roleId);
        // 查询当前角色未引用的资源权限
        List<Permission> permissionList = permissionService.findOtherPermission(roleId);
        mv.addObject("role", role);
        mv.addObject("permissionList", permissionList);
        mv.setViewName("role-permission-add");
        return mv;
    }

    /**
     * 给角色添加资源权限信息
     *
     * @param roleId        角色id
     * @param permissionIds 要添加的资源权限id集合
     * @return 角色列表视图
     * @throws Exception e
     */
    @RequestMapping("/addPermissionToRole.do")
    public String addPermissionToRole(String roleId, @RequestParam(name = "ids") String[] permissionIds) throws Exception {
        roleService.addPermissionToRole(roleId, permissionIds);
        return "redirect:findAll.do";
    }

    /**
     * 角色管理-详情
     *
     * @param mv 视图
     * @param roleId 角色id
     * @return 角色详情页面
     */
    @RequestMapping("/findById.do")
    public ModelAndView findById(ModelAndView mv, @RequestParam(name = "id") String roleId) throws Exception{
        Role role = roleService.findById(roleId);
        mv.addObject("role",role);
        mv.setViewName("role-show");
        return mv;
    }
}
